package com.woyou.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.woyou.Constants;
import com.woyou.bean.UserInfo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;

//存放�?��零散 但可以复用的业务逻辑
public class Utils {

	private static final String TAG = "Utils";
	private static Context mContext;

	public static final String DIR = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/woyou/";
	public static final String NAME = "userinfo.key";

	/**
	 * 将用户信息UserInfo写入到TF卡上
	 */
	public static void writeUserInfo2TF(UserInfo userInfo) {
		try {
			// 判断是否有sd卡
			if (Utils.hasSdcard()) {
				// 删除文件夹及文件
				Utils.delDir(DIR);
				File dir = new File(DIR);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File file = new File(dir, NAME);
				FileOutputStream fos = new FileOutputStream(file, true);
				ObjectOutputStream oos = new ObjectOutputStream(fos);
				oos.writeObject(userInfo);
				oos.close();
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将TF卡中的用户信息转换成Userinfo对象
	 * 
	 * @throws FileNotFoundException
	 */
	public static UserInfo readUserInfo4TF() {
		try {
			// 判断是否有sd卡
			if (Utils.hasSdcard()) {
				File dir = new File(DIR);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File file = new File(dir, NAME);
				FileInputStream fis = new FileInputStream(file);
				ObjectInputStream ois = new ObjectInputStream(fis);
				UserInfo userInfo = (UserInfo) ois.readObject();
				fis.close();
				ois.close();
				return userInfo;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 将TF卡上的UserInfo移除掉
	 */
	public static void removeUserInfo2TF() {
		try {
			// 判断是否有sd卡
			if (Utils.hasSdcard()) {
				// 删除文件夹及文件
				Utils.delDir(DIR);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static int ParseInt(String s) {
		int v = 0;
		try {
			v = Integer.parseInt(s);
		} catch (Exception e) {
		}
		return v;
	}

	public static float ParseFloat(String s) {
		float v = 0.0f;
		try {
			v = Float.parseFloat(s);
		} catch (Exception e) {
		}
		return v;
	}

	public static boolean isEmpty(List<?> list) {
		return list == null || list.size() == 0;
	}

	public static long getFileSizes(File f) throws Exception {// 取得文件大小
		long s = 0;
		if (f.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(f);
			s = fis.available();
		} else {
			f.createNewFile();
			System.out.println("文件不存在");
		}
		return s;
	}

	// 递归
	public static long getFileSize(File f) throws Exception// 取得文件夹大�?
	{
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	public static String FormetFileSize(long fileS) {// 转换文件大小
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	public static long getlist(File f) {// 递归求取目录文件个数
		long size = 0;
		File flist[] = f.listFiles();
		size = flist.length;
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getlist(flist[i]);
				size--;
			}
		}
		return size;

	}

	// // 打印图片缓存文件夹的信息
	// @SuppressWarnings("unused")
	// public static void LogImgCacheInfo(Context context) {
	// if (true)// �?��
	// return;
	//
	// try {
	// File cacheDir = StorageUtils.getCacheDirectory(context);
	// if (cacheDir.isDirectory()) { // 如果路径是文件夹的时�?
	// Log.i(TAG, "缓存图片文件个数    : " + getlist(cacheDir));
	// long fileSize = getFileSize(cacheDir);
	// Log.i(TAG, "缓存目录:" + cacheDir.getAbsolutePath() + "目录的大小为 :"
	// + FormetFileSize(fileSize));
	//
	// } else {
	// Log.i(TAG, " 文件个数           1");
	// Log.i(TAG, "文件");
	// long fileSizes = getFileSizes(cacheDir);
	// Log.i(TAG, cacheDir.getAbsolutePath() + "文件的大小为："
	// + FormetFileSize(fileSizes));
	// }
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	//
	// }

	/**
	 * 判断sd卡是否存�?
	 * 
	 * @return
	 */
	public static boolean hasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除目录
	 * 
	 * @param path
	 */
	public static void delDir(String path) {
		File dir = new File(path);
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					delDir(path + "/" + tmp[i].getName());
				} else {
					tmp[i].delete();
				}
			}
			dir.delete();
		}
	}

	public static String getVersionName(Context context) {
		mContext = context;
		try {
			// 获取packagemanager的实例
			PackageManager packageManager = context.getPackageManager();
			// getPackageName()是你当前类的包名，0代表是获取版本信息
			PackageInfo packInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			String version = packInfo.versionName;
			return version;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "";
	}

	/**
	 * 获取版本号
	 * 
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		mContext = context;
		try {
			PackageInfo myVersionManager = context.getPackageManager()
					.getPackageInfo(context.getPackageName(),
							PackageManager.GET_CONFIGURATIONS);
			return myVersionManager.versionCode;
		} catch (NameNotFoundException e) {
		}
		return -1;
	}

	/**
	 * 获取设备唯一标识码
	 * 
	 * @return 设备唯一标识码字符串
	 */
	public static String getDeviceCode(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(context.TELEPHONY_SERVICE);
		String deviceId = tm.getDeviceId();
		if (deviceId != null)
			return deviceId;

		if (Utils.isWifi(context)) {
			return Utils.getWiFiMacAdd(context);
		}

		if (Utils.isLAN(context)) {
			return Utils.getMacAddress();
		}

		return "";
	}

	public static String formatPrice(String price) {
		double value;
		try {
			value = Double.parseDouble(price);
		} catch (NumberFormatException e) {
			return price;
		}
		return formatPrice(value);
	}

	public static String formatNormalPrice(double price) {
		DecimalFormat dcmFmt = new DecimalFormat("0.00");
		return dcmFmt.format(price);
	}

	public static String formatNormalPrice(String price) {
		double value;
		try {
			value = Double.parseDouble(price);
		} catch (NumberFormatException e) {
			return price;
		}
		return formatNormalPrice(value);
	}

	public static String formatPrice(double price) {

		DecimalFormat dcmFmt = new DecimalFormat("0.00");
		String rv = dcmFmt.format(price);

		if (rv.endsWith(".00")) {
			rv = rv.substring(0, rv.length() - 3);
		} else if (rv.endsWith("0")) {
			rv = rv.substring(0, rv.length() - 1);
		}
		return rv;
	}

	/**
	 * 计算两个日期间的天数
	 * 
	 * @param fromDate
	 *            起始日期
	 * @param toDate
	 *            结束日期
	 * @return
	 * @throws ParseException
	 */
	public static int dateDiff(String fromDate, String toDate)
			throws ParseException {
		int days = 0;

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date from = df.parse(fromDate);
		Date to = df.parse(toDate);
		days = (int) Math.abs((to.getTime() - from.getTime())
				/ (24 * 60 * 60 * 1000));

		return days;
	}

	/**
	 * wifi是否打开
	 */
	public static boolean isWifiEnabled(Context context) {
		ConnectivityManager mgrConn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		TelephonyManager mgrTel = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
				.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
				.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
	}

	/**
	 * 判断当前网络是否是wifi网络
	 * 
	 * @param context
	 * @return boolean
	 */
	public static boolean isWifi(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	/**
	 * 判断当前网络是否是3G网络
	 * 
	 * @param context
	 * @return boolean
	 */
	public static boolean is3G(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			return true;
		}
		return false;
	}

	public static boolean isLAN(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
			return true;
		}
		return false;
	}

	/**
	 * 网络是否可用
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 测试WIFI信号强度
	 * 
	 * @param context
	 * @return
	 */
	public static int getWifiRssi(Context context) {
		WifiManager wifi_service = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifi_service.getConnectionInfo();
		return wifiInfo.getRssi();
	}

	/**
	 * ping ip地址
	 * 
	 * @param address
	 * @return
	 * @throws Exception
	 */
	public static boolean ping(String address) throws Exception {
		String s = "";
		StringBuffer buf = new StringBuffer();
		// c 4表示ping的次数
		// i 0.2表示指定收发信息的间隔秒数
		// w 3表示ping后3秒没有收到包就返回
		Process process = Runtime.getRuntime().exec(
				"/system/bin/ping -c 4 -i 0.2 -w 3 " + address);
		BufferedReader br = new BufferedReader(new InputStreamReader(
				process.getInputStream()));
		while ((s = br.readLine()) != null) {
			buf.append(s + "");
		}
		Log.i("Utils", buf.toString());
		int status = process.waitFor();
		if (status == 0)
			return true;
		return false;
	}

	/**
	 * 判断某个网页是否可以访问
	 * 
	 * @return
	 */
	public static boolean accessWeb(String address) {
		try {
			URL url = new URL(Constants.WEB_ADDRESS);
			HttpURLConnection httpUC = (HttpURLConnection) url.openConnection();
			httpUC.setConnectTimeout(3000);
			httpUC.setReadTimeout(3000);
			httpUC.connect();
			if (httpUC.getResponseCode() == HttpURLConnection.HTTP_OK) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 * 获取wifi mac地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getWiFiMacAdd(Context context) {
		WifiManager wifi = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}

	/**
	 * 读取linux mac地址文件
	 * 
	 * @param filePath
	 * @return
	 * @throws java.io.IOException
	 */
	public static String loadFileAsString(String filePath)
			throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
		}
		reader.close();
		return fileData.toString();
	}

	/*
	 * Get the STB MacAddress
	 */
	public static String getMacAddress() {
		try {
			return loadFileAsString("/sys/class/net/eth0/address")
					.toUpperCase().substring(0, 17);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void reset3G(Context context, boolean enable) {
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		Class<?> cmClass = connManager.getClass();
		Class<?>[] argClasses = new Class[1];
		argClasses[0] = boolean.class;
		// 反射ConnectivityManager中hide的方法setMobileDataEnabled，可以开启和关闭GPRS网络

		try {
			Method method = cmClass.getMethod("setMobileDataEnabled",
					argClasses);
			method.invoke(connManager, enable);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static int sumForReset3G = 0;

	public static int get3GResetSum() {
		// TODO Auto-generated method stub
		return sumForReset3G;
	}

	public static void reset3GCount() {
		sumForReset3G++;
	}

	@SuppressLint("SimpleDateFormat")
	public static String getDateStamp() {
		SimpleDateFormat stampFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss.SSS");
		return stampFormat.format(new Date());
	}

	public static long getTime() {
		return (new Date()).getTime();
	}

	@SuppressLint("SimpleDateFormat")
	public static String getOrderScoreDate(String sdate) {
		SimpleDateFormat stampFormat1 = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm:ss");
		SimpleDateFormat stampFormat2 = new SimpleDateFormat("MM-dd HH:mm");
		try {
			Date d = stampFormat1.parse(sdate);
			return stampFormat2.format(d);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdate.substring(5, sdate.lastIndexOf(":"));
	}

	public static String testLog1 = "3G";
	public static String testLog2 = "";
	public static String testLog3 = "";
	public static String testLog4 = "";
	public static String testLog5 = "";

	public static boolean flag3 = false;
	public static boolean flag4 = false;
	public static boolean flag5 = false;

	public static void setMobileDataEnabled(Context context, boolean enabled) {
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		Class<?> cmClass = connManager.getClass();
		Class<?>[] argClasses = new Class[1];
		argClasses[0] = boolean.class;
		// 反射ConnectivityManager中hide的方法setMobileDataEnabled，可以开启和关闭GPRS网络

		try {
			Method method = cmClass.getMethod("setMobileDataEnabled",
					argClasses);
			method.invoke(connManager, enabled);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
